﻿using CGT.OP.App_Start;
using CGT.OP.Common;
using CGT.OP.Models;
using OF.Component;
using OF.Component.BLL;
using OF.Component.DTO;
using OF.Component.Model;
using OF.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CGT.OP.Controllers
{
    public class ConfigController : BaseController
    {
        #region 省市业务开通
        [Authentication(MenuCode = "cgt40101")]
        public ActionResult CityOpenManage()
        {
            string rval = GetParam("provinceid");
            ViewBag.ProvinceId = rval;
            return View();
        }

        /// <summary>
        /// 根据省ID获取开通城市
        /// </summary>
        /// <param name="provinceId"></param>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetCityOpenCityByPid(int provinceId)
        {
            ResultData<IList<CityOpenInfo>> rData = new ResultData<IList<CityOpenInfo>>();
            IList<CityOpenInfo> list = CityOpenOperate.GetListByProviceId(provinceId);
            rData.data = list;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 开通城市
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult PassCity(CityOpenModel model)
        {
            ResultData<bool> rData = new ResultData<bool>();
            bool isSuccess = SetCityOpenStatus(model.CityId, model.CityName, 1);
            rData.data = isSuccess;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 关闭城市
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult CloseCity(int cityId)
        {
            ResultData<bool> rData = new ResultData<bool>();
            bool isSuccess = SetCityOpenStatus(cityId, "", 0);
            rData.data = isSuccess;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 设置开通城市状态
        /// </summary>
        /// <param name="cityId">城市ID</param>
        /// <param name="status">状态0:关闭1:开通</param>
        private bool SetCityOpenStatus(int cityId, string cityName, int status)
        {
            CityOpenInfo info = CityOpenOperate.QuerySingle(a => a.CityID == cityId && a.IsActive == 1);
            if (info != null)
            {
                info.Status = status;
                info.UpdatedDate = DateTime.Now;
                info.UpdatedUserID = CurrentUser().UserId;
                CityOpenOperate.Update(info);
                return true;
            }
            else
            {
                if (status == 1)
                {
                    info = new CityOpenInfo
                    {
                        CityID = cityId,
                        CityName = cityName,
                        CreatedDate = DateTime.Now,
                        CreatedUserID = CurrentUser().UserId,
                        Status = 1,
                        IsActive = 1
                    };
                    CityOpenOperate.Insert(info);
                    return true;
                }
                return false;
            }

        }
        #endregion

        #region 城市业务配置
        [Authentication(MenuCode = "cgt40101")]
        public ActionResult FormBusiness(int cityid, int provinceid, string cityname)
        {
            ViewBag.CityId = cityid;
            ViewBag.ProvinceId = provinceid;
            ViewBag.CityName = cityname;
            return View();
        }

        /// <summary>
        /// 业务配置列表
        /// </summary>
        /// <param name="cityId"></param>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetFormFieldCfgList()
        {
            string rval = GetParam("cityId");
            int cityId = EConvert.ToInt(rval, 0);
            Dictionary<int, BizTypeCityRelaInfo> dic = new Dictionary<int, BizTypeCityRelaInfo>();
            //获取业务配置
            IList<BizTypeCityRelaInfo> cfgList = BizTypeCityRelaOperate.QueryList(a => a.IsActive == 1 && a.CityID == cityId);
            foreach (var item in cfgList)
            {
                if (!dic.ContainsKey(item.BizTypeID))
                {
                    dic.Add(item.BizTypeID, item);
                }
            }
            //业务查询
            ResultData<List<BizTypeCityRelaDto>> rData = new ResultData<List<BizTypeCityRelaDto>>();
            List<BizTypeCityRelaDto> dtoList = new List<BizTypeCityRelaDto>();
            BasePageConditionFront pageObj = new BasePageConditionFront();
            pageObj.rows = GetPageSize();
            pageObj.page = GetPageIndex();
            IList<BizTypeDto> list = BizTypeOperate.SearchList(pageObj);
            foreach (var item in list)
            {
                BizTypeCityRelaDto obj = new BizTypeCityRelaDto();
                obj.MasterBizTypeName = item.MasterBizTypeName;
                obj.BizTypeID = item.BizTypeID;
                obj.BizTypeName = item.BizTypeName;
                if (dic.ContainsKey(item.BizTypeID))
                {
                    BizTypeCityRelaInfo info = dic[item.BizTypeID];
                    obj.Status = info.Status;
                    obj.CreatedDate = info.CreatedDate;
                    obj.BizTypeCityRelaID = info.BizTypeCityRelaID;
                }
                dtoList.Add(obj);
            }
            rData.data = dtoList.ToList();
            rData.message = pageObj.total.ToString();
            return ReturnResult(rData);
        }

        /// <summary>
        /// 保存业务配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ContentResult SaveFormFieldCfg(FormFieldCfgModel model)
        {
            int cityID = model.CityId;
            string[] strFIDAll = model.BizTypeIds.Split(',');
            ResultData<bool> rData = new ResultData<bool>();
            IList<BizTypeCityRelaInfo> list = BizTypeCityRelaOperate.QueryList(a => a.CityID == cityID && a.IsActive == 1);
            if (strFIDAll.Length == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有选择业务";
                return ReturnResult(rData);
            }
            if (cityID == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "城市ID为空";
                return ReturnResult(rData);
            }
            foreach (var item in strFIDAll)
            {
                var obj = list.Where(a => a.BizTypeID == int.Parse(item)).ToList();
                if (obj.Count > 0)
                {
                    BizTypeCityRelaInfo oInfo = obj[0];
                    if (oInfo.Status == 0)
                    {
                        oInfo.Status = 1;
                        oInfo.UpdatedDate = DateTime.Now;
                        oInfo.UpdatedUserID = CurrentUser().UserId;
                        BizTypeCityRelaOperate.Update(oInfo);
                    }
                    continue;
                }
                BizTypeCityRelaInfo info = new BizTypeCityRelaInfo
                {
                    BizTypeID = int.Parse(item),
                    IsActive = 1,
                    CfgDesc = "",
                    CityID = cityID,
                    CreatedDate = DateTime.Now,
                    CreatedUserID = CurrentUser().UserId,
                    Status = 1,
                    UpdatedDate = DateTime.MinValue,
                    UpdatedUserID = 0
                };
                BizTypeCityRelaOperate.Insert(info);
            }
            rData.data = true;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 取消业务配置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ContentResult CancelFormFieldCfg(FormFieldCfgModel model)
        {
            int cityID = model.CityId;
            string[] strFIDAll = model.BizTypeIds.Split(',');
            ResultData<bool> rData = new ResultData<bool>();

            if (strFIDAll.Length == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有选择业务";
                return ReturnResult(rData);
            }
            if (cityID == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "城市ID为空";
                return ReturnResult(rData);
            }
            List<int> intIds = new List<int>();
            foreach (var item in strFIDAll)
            {
                intIds.Add(int.Parse(item));
            }
            rData.data = BizTypeCityRelaOperate.BatchCancelCfg(intIds, cityID);
            return ReturnResult(rData);
        }
        #endregion

        #region 表单配置
        [Authentication(MenuCode = "cgt40101")]
        public ActionResult ConfigForm(int cgfid, int provinceid, string cityname)
        {
            ViewBag.CgfId = cgfid;
            ViewBag.ProvinceId = provinceid;
            ViewBag.CityName = cityname;
            ViewBag.CityId = 0;
            ViewBag.BizTypeName = "";
            BizTypeCityRelaInfo info = BizTypeCityRelaOperate.GetByID(cgfid);
            if (info != null)
            {
                ViewBag.CityId = info.CityID;
                BizTypeInfo bizInfo = BizTypeOperate.GetByID(info.BizTypeID);
                if (bizInfo != null)
                {
                    ViewBag.BizTypeName = bizInfo.BizTypeName;
                    ViewBag.BizTypeId = bizInfo.BizTypeID;
                }
            }
            return View();
        }

        /// <summary>
        /// 获取所有字段类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetFormFieldList(int cfgId)
        {
            ResultData<IList<FormFieldDto>> rData = new ResultData<IList<FormFieldDto>>();
            IList<FormFieldDto> list = FormFieldOperate.GetFormFieldRelaedList(cfgId);
            rData.data = list;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 保存配置字段
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult SaveFormFieldRela(FormFieldRelaModel model)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (model.FormFieldCfgID == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有配置业务";
                return ReturnResult(rData);
            }
            if (model.FormFieldIds == "")
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有选择字段";
                return ReturnResult(rData);
            }
            FormFieldRelaOperate.BatchCancelCfg(model.FormFieldCfgID, CurrentUser().UserId);
            string[] strFIDAll = model.FormFieldIds.Split(',');
            string[] strSortArr = model.FieldSorts.Split(',');
            int i = 0;
            foreach (var item in strFIDAll)
            {
                FormFieldRelaInfo info = new FormFieldRelaInfo
                {
                    BizTypeCityRelaID = model.FormFieldCfgID,
                    FormFieldID = int.Parse(item),
                    FieldSort = int.Parse(strSortArr[i]),
                    IsActive = 1,
                    CreatedDate = DateTime.Now,
                    CreatedUserID = CurrentUser().UserId,
                    UpdatedDate = DateTime.MinValue,
                    UpdatedUserID = 0
                };
                FormFieldRelaOperate.Insert(info);
                i++;
            }
            rData.data = true;
            return ReturnResult(rData);
        }
        #endregion

        #region 价格配置
        [Authentication(MenuCode = "cgt40101")]
        public ActionResult ConfigPrice(int cgfid, int provinceid, string cityname)
        {
            ViewBag.CgfId = cgfid;
            ViewBag.ProvinceId = provinceid;
            ViewBag.CityName = cityname;
            ViewBag.CityId = 0;
            ViewBag.BizTypeName = "";
            ViewBag.BizTypeId = 0;
            BizTypeCityRelaInfo info = BizTypeCityRelaOperate.GetByID(cgfid);
            if (info != null)
            {
                ViewBag.CityId = info.CityID;
                BizTypeInfo bizInfo = BizTypeOperate.GetByID(info.BizTypeID);
                if (bizInfo != null)
                {
                    ViewBag.BizTypeName = bizInfo.BizTypeName;
                    ViewBag.BizTypeId = bizInfo.BizTypeID;
                }
            }
            return View();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveConfigPrice(NetWorkFeeConfigModel model)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (model.CityID == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有选择城市";
                return ReturnResult(rData);
            }
            if (model.BizTypeId == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有配置业务";
                return ReturnResult(rData);
            }
            if (model.FeeNameArr == "")
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有费用名称";
                return ReturnResult(rData);
            }
            if (model.FeeArr == "")
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有费用金额";
                return ReturnResult(rData);
            }

            string[] strNameAll = model.FeeNameArr.Split(',');
            string[] strFeeArr = model.FeeArr.Split(',');
            string[] strFeeType = model.FeeTypeArr.Split(',');

            if (string.IsNullOrWhiteSpace(model.FeeConfigIds))
            {
                int i = 0;
                foreach (var item in strNameAll)
                {
                    NetWorkFeeConfigInfo info = new NetWorkFeeConfigInfo
                    {
                        BizTypeID = model.BizTypeId,
                        CityID = model.CityID,
                        Fee = EConvert.ToDecimal(strFeeArr[i], 0),
                        FeeName = item,
                        FeeType = EConvert.ToInt(strFeeType[i], 0),
                        IsActive = 1,
                        CreatedDate = DateTime.Now,
                        CreatedUserID = CurrentUser().UserId,
                        UpdatedDate = DateTime.MinValue,
                        UpdatedUserID = 0
                    };
                    NetWorkFeeConfigOperate.Insert(info);
                    i++;
                }
            }
            else
            {
                string[] strIds = model.FeeConfigIds.Split(',');
                int i = 0;
                List<int> ids = new List<int>();
                foreach (var item in strNameAll)
                {
                    int id = 0;
                    NetWorkFeeConfigInfo info = null;
                    if (strIds.Length > i)
                    {
                        id = EConvert.ToInt(strIds[i], 0);
                        info = NetWorkFeeConfigOperate.GetByID(id);
                    }

                    if (info != null)
                    {
                        info.Fee = EConvert.ToDecimal(strFeeArr[i], 0);
                        info.FeeName = item;
                        info.FeeType = EConvert.ToInt(strFeeType[i], 0);
                        info.UpdatedDate = DateTime.Now;
                        info.UpdatedUserID = CurrentUser().UserId;
                        NetWorkFeeConfigOperate.Update(info);
                        ids.Add(id);
                    }
                    else
                    {
                        NetWorkFeeConfigInfo infos = new NetWorkFeeConfigInfo
                        {
                            BizTypeID = model.BizTypeId,
                            CityID = model.CityID,
                            Fee = EConvert.ToDecimal(strFeeArr[i], 0),
                            FeeName = item,
                            FeeType = EConvert.ToInt(strFeeType[i], 0),
                            IsActive = 1,
                            CreatedDate = DateTime.Now,
                            CreatedUserID = CurrentUser().UserId,
                            UpdatedDate = DateTime.MinValue,
                            UpdatedUserID = 0
                        };
                        int newId = NetWorkFeeConfigOperate.Insert(infos);
                        ids.Add(newId);
                    }
                    i++;
                }
                NetWorkFeeConfigOperate.BatchCancelFeeConfigByIds(ids, model.CityID, model.BizTypeId, CurrentUser().UserId);
            }

            rData.data = true;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 根据城市、业务类型获取所有价格配置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetNetWorkFeeConfigList(int cityId, int bizType)
        {
            ResultData<IList<NetWorkFeeConfigInfo>> rData = new ResultData<IList<NetWorkFeeConfigInfo>>();
            IList<NetWorkFeeConfigInfo> list = NetWorkFeeConfigOperate.QueryList(a => a.IsActive == 1 && a.CityID == cityId && a.BizTypeID == bizType);
            rData.data = list;
            return ReturnResult(rData);
        }
        #endregion

        #region 网办订单过期配置
        [Authentication(MenuCode = "cgt40101")]
        public ActionResult ConfigOrderExpire(int cgfid, int provinceid, string cityname)
        {
            ViewBag.CgfId = cgfid;
            ViewBag.ProvinceId = provinceid;
            ViewBag.CityName = cityname;
            ViewBag.CityId = 0;
            ViewBag.BizTypeName = "";
            ViewBag.BizTypeId = 0;
            BizTypeCityRelaInfo info = BizTypeCityRelaOperate.GetByID(cgfid);
            if (info != null)
            {
                ViewBag.CityId = info.CityID;
                BizTypeInfo bizInfo = BizTypeOperate.GetByID(info.BizTypeID);
                if (bizInfo != null)
                {
                    ViewBag.BizTypeName = bizInfo.BizTypeName;
                    ViewBag.BizTypeId = bizInfo.BizTypeID;
                }
            }
            return View();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveOrderExpire(NetworkOrderExpireModel model)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (model.CityID == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有选择城市";
                return ReturnResult(rData);
            }
            if (model.BizTypeId == 0)
            {
                rData.status = -1;
                rData.data = false;
                rData.message = "没有配置业务";
                return ReturnResult(rData);
            }

            NetworkOrderExpireInfo info = NetworkOrderExpireOperate.QuerySingle(a => a.IsActive == 1 && a.CityID == model.CityID && a.BizTypeID == model.BizTypeId);
            if (info != null)
            {
                info.ExpireInterval = model.ExpireInterval;
                info.UpdatedDate = DateTime.Now;
                info.UpdatedUserID = CurrentUser().UserId;
                NetworkOrderExpireOperate.Update(info);
            }
            else
            {
                info = new NetworkOrderExpireInfo
                {
                    BizTypeID = model.BizTypeId,
                    CityID = model.CityID,
                    ExpireInterval = model.ExpireInterval,
                    IsActive = 1,
                    CreatedDate = DateTime.Now,
                    CreatedUserID = CurrentUser().UserId,
                    UpdatedDate = DateTime.MinValue,
                    UpdatedUserID = 0
                };
                NetworkOrderExpireOperate.Insert(info);
            }
            rData.data = true;
            return ReturnResult(rData);
        }

        /// <summary>
        /// 根据城市、业务类型获取所有价格配置
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetNetWorkOrderExpireInfo(int cityId, int bizType)
        {
            ResultData<NetworkOrderExpireInfo> rData = new ResultData<NetworkOrderExpireInfo>();
            NetworkOrderExpireInfo obj = NetworkOrderExpireOperate.QuerySingle(a => a.IsActive == 1 && a.CityID == cityId && a.BizTypeID == bizType);
            rData.data = obj;
            return ReturnResult(rData);
        }
        #endregion

        #region 快递模版配置
        [Authentication(MenuCode = "cgt40101")]
        //视图
        public ActionResult ConfigExpressTemplate(int cgfid, int provinceid, string cityname)
        {
            ViewBag.CgfId = cgfid;
            ViewBag.ProvinceId = provinceid;
            ViewBag.CityName = cityname;
            ViewBag.CityId = 0;
            ViewBag.BizTypeName = "";
            ViewBag.BizTypeId = 0;
            BizTypeCityRelaInfo info = BizTypeCityRelaOperate.GetByID(cgfid);
            if (info != null)
            {
                ViewBag.CityId = info.CityID;
                BizTypeInfo bizInfo = BizTypeOperate.GetByID(info.BizTypeID);
                if (bizInfo != null)
                {
                    ViewBag.BizTypeName = bizInfo.BizTypeName;
                    ViewBag.BizTypeId = bizInfo.BizTypeID;
                }
            }
            var expressList = ExpressCompanyOperate.QueryList(x => x.IsActive == 1);
            ViewBag.ExpressList = expressList;
            return View();
        }
        //快递模版分部视图
        public PartialViewResult ConfigExpressTemplatePartial(ExpressTemplateCondition pageObj)
        {
            pageObj.rows = GetPageSize();
            pageObj.page = GetPageIndex();
            #region 拼接where条件
            var strWhere = " IsActive=1 ";
            if (pageObj.BizTypeId > 0)
                strWhere += string.Format(" AND BizTypeID={0}", pageObj.BizTypeId);
            if (!string.IsNullOrWhiteSpace(pageObj.TemplateName))
                strWhere += string.Format(" AND CHARINDEX('{0}', TemplateName)>0 ", pageObj.TemplateName);
            if (pageObj.ExpressID > 0)
                strWhere += string.Format(" AND ExpressCompanyID={0}", pageObj.ExpressID);
            #endregion
            var outCount = 0;
            var list = ExpressFeeTplOperate.Search(out outCount, pageObj.page,
                                         pageObj.rows, strWhere, "ExpressFeeTplID", true);
            //快递公司数量极少，所以查出来再匹配
            var expressList = ExpressCompanyOperate.QueryList(x => x.IsActive == 1).ToList();
            var models = new List<ExpressTemplateDto>();
            //匹配快递名称
            foreach (var item in list)
            {
                var model = new ExpressTemplateDto();
                item.MergeTo(model);
                var express = expressList.Find(x => x.ExpressCompanyID == model.ExpressCompanyID);
                model.ExpressCompanyName = "";
                if (express != null)
                    model.ExpressCompanyName = expressList.Find(x => x.ExpressCompanyID == model.ExpressCompanyID).CompanyName;
                models.Add(model);
            }
            ViewBag.outCount = outCount;
            return PartialView(models);
        }
        //add、edit页面
        [Authentication(MenuCode = "cgt40101")]
        public ActionResult ConfigExpressTemplateEdit()
        {
            ViewBag.ExpressList = null;//快递列表
            ViewBag.TplInfo = null;//模版对象
            ViewBag.TplCityList = null;//模版配置的城市
            ViewBag.TplCityStr = "";
            var bizTypeId = GetParam("bizTypeId");
            ViewBag.BizTypeId = bizTypeId;
            var expressList = ExpressCompanyOperate.QueryList(x => x.IsActive == 1);
            ViewBag.ExpressList = expressList;
            var templateId = EConvert.ToInt(GetParam("id"));
            #region 查询同业务其他模版已经配置的城市
            var existCityStr = GetOtherTplExistCity(templateId, EConvert.ToInt(bizTypeId));
            ViewBag.TplExistCityStr = existCityStr;
            #endregion
            //edit
            if (templateId > 0)
            {
                //获取已经该模版配置的城市列表
                var cityList = ExpressFeeTplCityOperate.QueryList(x => x.ExpressFeeTplID == templateId);
                var cityStr = "";
                if (cityList.Count() > 0)
                    cityStr = cityList.Aggregate("", (strs, cityB) => strs + cityB.CityID.ToString() + ",");
                if (!string.IsNullOrWhiteSpace(cityStr))
                    cityStr = cityStr.Substring(0, cityStr.Length - 1);
                var template = ExpressFeeTplOperate.QuerySingle(x => x.ExpressFeeTplID == templateId);
                ViewBag.TplInfo = template;
                ViewBag.TplCityList = cityList;
                ViewBag.TplCityStr = cityStr;
            }
            return View();
        }
        [HttpPost]
        public ContentResult ConfigExpressTemplateDelete()
        {
            ResultData<int> rData = new ResultData<int>();
            int id = EConvert.ToInt(GetParam("id"));
            try
            {
                var entity = ExpressFeeTplOperate.QuerySingle(x => x.ExpressFeeTplID == id);
                if (entity != null)
                {
                    entity.IsActive = 0;
                    ExpressFeeTplOperate.Update(entity);
                    //逻辑删除模版下的所有城市
                    ExpressFeeTplCityOperate.LogicDeleteByTplId(entity.ExpressFeeTplID);
                }
                else
                {
                    rData.status = -1;
                }
            }
            catch (Exception ex)
            {
                rData.status = -1;
            }
            return ReturnResult(rData);
        }
        //保存
        public ContentResult ConfigExpressSave(ExpressFeeTplSaveModel saveModel)
        {
            ResultData<long> rData = new ResultData<long>();
            var tplEntity = new ExpressFeeTplInfo()
            {
                BizTypeID = saveModel.BizTypeId,
                TemplateName = saveModel.TplName,
                ExpressCompanyID = saveModel.ExpressId,
                ExpressFee = saveModel.Price,
                Remark = saveModel.Remark,
                IsActive = 1
            };
            try
            {
                //清理、删除覆盖同业务其他模版下重复的城市,并记入覆盖历史记录表
                if (!string.IsNullOrWhiteSpace(saveModel.SelExistCitiesStr))
                {
                    //根据业务ID取同业务所有模版   编辑页面也无需排除当前模版，因为就算是编辑，也会先全部删除城市再批量插入城市。
                    IList<ExpressFeeTplInfo> tplList = ExpressFeeTplOperate.QueryList(x => x.IsActive == 1 && x.BizTypeID == saveModel.BizTypeId).ToList();
                    //拼接模版id，逗号间隔
                    var tplStr = "";
                    if (tplList.Count() > 0)
                        tplStr = tplList.Aggregate("", (strs, tpl) => strs + tpl.ExpressFeeTplID.ToString() + ",");
                    if (!string.IsNullOrWhiteSpace(tplStr))
                        tplStr = tplStr.Substring(0, tplStr.Length - 1);
                    var existStr = saveModel.SelExistCitiesStr;
                    var strWhere = " 1=1 ";
                    //查询同业务所有模板内包含需要覆盖城市的item。
                    strWhere += string.Format("AND ExpressFeeTplID in ({0})  AND CityID in ({1})", tplStr, existStr);
                    var outCount = 0;
                    IList<ExpressFeeTplCityInfo> existCityList = ExpressFeeTplCityOperate.Search(out outCount, 1, 5000, strWhere, "ExpressFeeTplCity", true);
                    var inStr = "";
                    var historyList = new List<ExpressFeeTplCityHistoryInfo>();
                    if (existCityList.Count > 0)
                    {
                        foreach (var c in existCityList)
                        {
                            inStr += c.ExpressFeeTplCity + ",";
                            var history = new ExpressFeeTplCityHistoryInfo()
                            {
                                ExpressFeeTplCity = c.ExpressFeeTplCity,
                                ExpressFeeTplID = c.ExpressFeeTplID,
                                CityID = c.CityID,
                                UpdateDate = DateTime.Now,
                                UpdatedUserID = this.CurrentUser().UserId
                            };
                            historyList.Add(history);
                        }
                        inStr = inStr.Substring(0, inStr.Length - 1);
                        //批量删除
                        ExpressFeeTplCityOperate.BatchDelete(inStr);
                        //批量插入历史记录表
                        ExpressFeeTplCityHistoryOperate.BatchInsert(historyList);
                    }
                }

                if (saveModel.TplId <= 0)
                {
                    //add
                    tplEntity.CreatedDate = DateTime.Now;
                    tplEntity.CreatedUserID = this.CurrentUser().UserId;
                    var tplId = ExpressFeeTplOperate.Insert(tplEntity);
                    rData.data = tplId;
                    if (!string.IsNullOrWhiteSpace(saveModel.SelCitiesStr))
                    {
                        var citys = GetBatchInserExpressTplEntitys(saveModel.SelCitiesStr, tplId);
                        if (citys.Count > 0)
                            //批量插入
                            ExpressFeeTplCityOperate.BatchInsert(citys);
                    }
                }
                else
                {
                    //edit
                    tplEntity.ExpressFeeTplID = saveModel.TplId;
                    tplEntity.UpdatedDate = DateTime.Now;
                    tplEntity.UpdatedUserID = this.CurrentUser().UserId;
                    //更新模版
                    ExpressFeeTplOperate.Update(tplEntity);
                    //先删除当前模板下所有城市
                    var removeCitys = ExpressFeeTplCityOperate.QueryList(x => x.ExpressFeeTplID == tplEntity.ExpressFeeTplID);
                    if (removeCitys.Count > 0)
                    {
                        var inStr = "";
                        foreach (var c in removeCitys)
                        {
                            inStr += c.ExpressFeeTplCity + ",";
                        }
                        inStr = inStr.Substring(0, inStr.Length - 1);
                        ExpressFeeTplCityOperate.BatchDelete(inStr);
                    }
                    //批量插入城市
                    var citys = GetBatchInserExpressTplEntitys(saveModel.SelCitiesStr, saveModel.TplId);
                    if (citys.Count > 0)
                        //批量插入
                        ExpressFeeTplCityOperate.BatchInsert(citys);
                }

            }
            catch (Exception ex)
            {
                rData.status = -1;
                rData.message = "处理失败，请重新设置";
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 获取快递-城市-价格配置模版批量插入的list<Entity>
        /// </summary>
        /// <param name="selCitysStr">城市id字符串，逗号间隔</param>
        /// <param name="tplId">模板ID</param>
        /// <returns>模板城市实体list</returns>
        private List<ExpressFeeTplCityInfo> GetBatchInserExpressTplEntitys(string selCitysStr, int tplId)
        {

            var cityArr = selCitysStr.Split(',');
            var citys = new List<ExpressFeeTplCityInfo>();
            foreach (var cityId in cityArr)
            {
                var cityEntity = new ExpressFeeTplCityInfo()
                {
                    ExpressFeeTplID = tplId,
                    CityID = EConvert.ToInt(cityId),
                    CreatedDate = DateTime.Now,
                    UpdatedDate = DateTime.Now,
                    CreatedUserID = this.CurrentUser().UserId,
                    UpdatedUserID = this.CurrentUser().UserId,
                    IsActive = 1
                };
                citys.Add(cityEntity);
            }
            return citys;
        }

        /// <summary>
        ///  获取同业务其他模版已经配置过的城市Id,字符串逗号间隔
        /// </summary>
        /// <returns>string</returns>
        private string GetOtherTplExistCity(int templateId, int bizTypeId)
        {
            var existCityStr = "";
            IList<ExpressFeeTplInfo> tplList = new List<ExpressFeeTplInfo>();
            //如果存在模版id，则查询除该模版外的 其他模板已经存在的城市
            if (templateId > 0)
                tplList = ExpressFeeTplOperate.QueryList(x => x.IsActive == 1 && x.BizTypeID == bizTypeId && x.ExpressFeeTplID != templateId).ToList();
            else
                tplList = ExpressFeeTplOperate.QueryList(x => x.IsActive == 1 && x.BizTypeID == bizTypeId).ToList();
            //拼接模版id，逗号间隔
            var tplStr = "";
            if (tplList.Count() > 0)
                tplStr = tplList.Aggregate("", (strs, tpl) => strs + tpl.ExpressFeeTplID.ToString() + ",");
            if (!string.IsNullOrWhiteSpace(tplStr))
                tplStr = tplStr.Substring(0, tplStr.Length - 1);
            //根据拼接的模版id  拿到已经配置过的城市ID
            if (!string.IsNullOrWhiteSpace(tplStr))
            {
                var strWhere = " 1=1 ";
                strWhere += string.Format(" AND ExpressFeeTplID in ({0})", tplStr);
                var outCount = 0;
                IList<ExpressFeeTplCityInfo> existCityList = ExpressFeeTplCityOperate.Search(out outCount, 1, 5000, strWhere, "ExpressFeeTplCity", true);
                existCityStr = existCityList.Aggregate("", (strs, city) => strs + city.CityID.ToString() + ",");
                if (!string.IsNullOrWhiteSpace(existCityStr))
                    existCityStr = existCityStr.Substring(0, existCityStr.Length - 1);
            }
            return existCityStr;
        }
        #endregion

        #region 配置说明
        //  [Authentication(MenuCode = "cgt40101")]
        public ActionResult ConfigGuidance(int cgfid, int provinceid, string cityname)
        {
            ViewBag.CgfId = cgfid;
            ViewBag.ProvinceId = provinceid;
            ViewBag.CityName = cityname;
            ViewBag.CityId = 0;
            ViewBag.BizTypeName = "";
            BizTypeCityRelaInfo info = BizTypeCityRelaOperate.GetByID(cgfid);
            if (info != null)
            {
                ViewBag.CityId = info.CityID;
                BizTypeInfo bizInfo = BizTypeOperate.GetByID(info.BizTypeID);
                if (bizInfo != null)
                {
                    ViewBag.BizTypeName = bizInfo.BizTypeName;
                    ViewBag.BizTypeId = bizInfo.BizTypeID;
                }
            }
            return View();
        }

        /// <summary>
        /// 保存办事指南
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult SaveGuidance(GuidanceModel model)
        {
            ResultData<int> rData = new ResultData<int>();
            GuidanceInfo info = GuidanceOperate.QuerySingle(a => a.CityID == model.CityID && a.BizTypeID == model.BizTypeID && a.IsActive == 1);
            try
            {
                if (info == null)
                {
                    info = new GuidanceInfo();
                    info.BizTypeID = model.BizTypeID;
                    info.IsActive = 1;
                    info.CreatedDate = DateTime.Now;
                    info.CreatedUserID = CurrentUser().UserId;
                    info.CityID = model.CityID;
                    info.GuidanceHtml = Ajax_decode(model.GuidanceHtml);
                    info.GuidanceWxMini = model.GuidanceWxMini;
                    info.UpdatedDate = DateTimeHelper.MinDateTime();
                    rData.data = GuidanceOperate.Insert(info);
                }
                else
                {
                    info.UpdatedDate = DateTime.Now;
                    info.GuidanceHtml = Ajax_decode(model.GuidanceHtml);
                    info.GuidanceWxMini = model.GuidanceWxMini;
                    info.UpdatedUserID = CurrentUser().UserId;
                    GuidanceOperate.Update(info);
                    rData.data = model.GuidanceID;
                }
            }
            catch (Exception ex)
            {
                rData.status = -1;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="cityId"></param>
        /// <param name="bizTypeId"></param>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetGuidanceInfo(int cityId, int bizTypeId)
        {
            ResultData<GuidanceInfo> rData = new ResultData<GuidanceInfo>();
            GuidanceInfo info = GuidanceOperate.QuerySingle(a => a.CityID == cityId && a.BizTypeID == bizTypeId && a.IsActive == 1);
            rData.data = info;
            return ReturnResult(rData);
        }

        private string Ajax_decode(string str)
        {
            str = str.Replace("{$bai$}", "%");
            str = str.Replace("{$dan$}", "'");
            str = str.Replace("{$shuang$}", "\"");
            str = str.Replace("{$kong$}", " ");
            str = str.Replace("{$zuojian$}", "<");
            str = str.Replace("{$youjian$}", ">");
            str = str.Replace("{$and$}", "&");
            str = str.Replace("{$tab$}", "\t");
            str = str.Replace("{$jia$}", "+");
            str = str.Replace("'", "''");
            return str;
        }
        #endregion

        #region 配置预览
        /// <summary>
        /// 配置预览
        /// </summary>
        /// <param name="cgfid"></param>
        /// <param name="provinceid"></param>
        /// <param name="cityname"></param>
        /// <returns></returns>
        public ActionResult ConfigView(int cgfid, int provinceid, string cityname)
        {
            ViewBag.CgfId = cgfid;
            ViewBag.ProvinceId = provinceid;
            ViewBag.CityName = cityname;
            ViewBag.CityId = 0;
            ViewBag.BizTypeName = "";
            BizTypeCityRelaInfo info = BizTypeCityRelaOperate.GetByID(cgfid);
            if (info != null)
            {
                ViewBag.CityId = info.CityID;
                BizTypeInfo bizInfo = BizTypeOperate.GetByID(info.BizTypeID);
                if (bizInfo != null)
                {
                    ViewBag.BizTypeName = bizInfo.BizTypeName;
                    ViewBag.BizTypeId = bizInfo.BizTypeID;
                }
            }
            return View();
        }

        /// <summary>
        /// 获取排序后所有字段类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult GetFormFieldListSort(int cfgId, int cityId, int bizTypeId)
        {
            BusinessView bv = new BusinessView();
            ResultData<BusinessView> rData = new ResultData<BusinessView>();
            IList<FormFieldDto> list = FormFieldOperate.GetFormFieldRelaedList(cfgId);
            IList<ExpressCompanyInfo> exList = ExpressCompanyOperate.GetInfoByBizTypeAndCityId(cityId, bizTypeId);
            foreach (var item in exList)
            {
                item.Logo = string.Format("{0}{1}", ConfigHelper.GetValue("ExpressImageSrc"), item.Logo);
            }
            IList<NetWorkFeeConfigInfo> feeList = NetWorkFeeConfigOperate.QueryList(a => a.BizTypeID == bizTypeId && a.CityID == cityId && a.IsActive == 1);
            bv.FormFieldList = list.Where(a => a.RelaID > 0).OrderBy(a => a.FieldSort).ToList();
            bv.ExpressList = exList;
            bv.FeeList = feeList;
            rData.data = bv;
            return ReturnResult(rData);
        }
        #endregion
    }
}